// 录音
export const record = function () {
  window.navigator.mediaDevices.getUserMedia({ audio: true }).then((stream) => {
    const mediaRecorder = new MediaRecorder(stream);
    const chunks = [];
    mediaRecorder.ondataavailable = (e) => {
      chunks.push(e.data);
    };
    mediaRecorder.onstop = () => {
      const blob = new Blob(chunks, { type: 'audio/webm' }); // 可换成 'audio/mp3' 或其他格式
      console.log(blob)
      uploadAudio(blob);
    };
    mediaRecorder.start();
    setTimeout(() => {
      mediaRecorder.stop(); // 录制5秒停止
    }, 5000);
  }).catch((err) => {
    console.error('获取麦克风权限失败:', err);
  });
}
// 上传录音
export function uploadAudio(blob) {
  const formData = new FormData();
  formData.append('audio', blob, 'recording.webm'); // 文件名随便取
  fetch('/api/upload-audio', {
    method: 'POST',
    body: formData,
  }).then(response => response.json())
    .then(data => console.log('上传成功:', data))
    .catch(error => console.error('上传失败:', error));
}